import HeadingGenerate from "./headingGenerate";
import {App} from "obsidian";

export default class HeadingDispatch {
	private app: App;
	private fileContent: string;
	private tags: string[];
	constructor(app: App, fileContent: string, tags: string[] = []) {
		this.app = app;
		this.fileContent = fileContent;
		this.tags = tags;
	}
	public dispatchToHeading(heading: string, content: string) {
		// 没有找到目标heading，则要用cascade heading方式带出上级heading
		if (!HeadingDispatch.findOffset(heading, this.fileContent)) {
			const vaultStartLocation = "1_Inbox/Diary";
			const ingoredHeaders = ["## 🕓今日事项", "## ✒️日常笔记", "## 🔔待办提醒", "## ✏思考总结"];
			const ignoredSuffixArray = [".excalidraw.md"];
			// 如果没找到heading，会报错并且跳过这条memo
			let generateHeadings = new HeadingGenerate(this.app, vaultStartLocation, ingoredHeaders, ignoredSuffixArray);
			this.fileContent = generateHeadings.selectSuggestion(heading, this.fileContent);  // heading = "#### 交银保险资管工作"
		}
		// 带出cascade heading后再找一次heading
		let position = HeadingDispatch.findOffset(heading, this.fileContent);
		const startOffset = position.endOffset;
		this.fileContent = this.fileContent.slice(0, startOffset).trimEnd() + `\n${this.appendGeneralTags(content, this.tags)}\n` + this.fileContent.slice(startOffset).trimStart();
		return this.fileContent;
	}
	private static findOffset(heading: string, content: string) {
		// const regex = new RegExp(`(?<=[\\n\\r])#+?${heading}(?=[\\n\\r]|$)`);
		const regex = new RegExp(`(?<=[\\n\\r])#+? ?(\\s|\\S)?${heading}(?=[\\n\\r]|$)`);
		const match = regex.exec(content);
		if (match) {
			return {startOffset: match.index, endOffset: match.index + match[0].length};
		} else {
			console.log(`not found heading ${heading} in: \n ${content}`);
			return null
		}
	}
	private appendGeneralTags(content: string, generalTags: string[]): string {
		let resultConent = content;
		for (const tag of generalTags) {
			resultConent = `${resultConent.trimEnd()} ${tag}`;
		}
		return resultConent
	}
}
